const axios = require('axios')
require('dotenv').config()
const { Client, GatewayIntentBits } = require('discord.js')

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildPresences,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
  ],
})

const twilio = require('twilio')(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN
)

const friendsChannelId = '1088784663583137856'
const myUserId = '953611009111773235'

const express = require('express')
const app = express()
app.use(
  express.urlencoded({
    extended: true,
  })
)

function extractNumbers(str) {
  const regex = /\.\#\d+'/
  console.log(str)
  const match = str.match(regex)
  if (match) {
    return match[0].slice(2, -1)
  }
  return 'error extract number'
}

function sendSMS(sms) {
  twilio.messages.create({
    body: sms,
    to: process.env.PERSONAL_NUMBER,
    from: process.env.TWILIO_NUMBER,
  })
}

app.post('/sms')

client.on('messageCreate', function (message) {
  //   if (message.author.bot) return;
  console.log(extractNumbers(message.content))
  console.log(message.attachments.size)
  if (message.attachments.size > 0) {
    console.log(message.content)
    var map = message.attachments
    var at = map.get([...map.keys()][0])
    console.log(at.url)

    axios
      .post('http://172.18.66.120:9000/save_image', {
        id: extractNumbers(message.content),
        url: at.url,
      })
      .then((response) => {
        //  console.log(response);
      })
      .catch((error) => {
        console.log(error)
      })
  }
})
app.listen(3000, () => {
  console.log('Listening on port 3000')
})

console.log('bot token=' + process.env.BOT_TOKEN)
client.login(process.env.BOT_TOKEN)
